<?php
declare (strict_types=1);

namespace app\api\controller;

use app\api\BaseController;
use app\api\service\UserService;
use app\api\validate\UserLoginValidate;
use app\service\SystemUploadService;
use app\traits\UserTrait;
use think\helper\Arr;
use think\response\Json;

class User extends BaseController
{
    use UserTrait;

    private UserService $service;

    public function initialize()
    {
        $this->service = new UserService();
        parent::initialize(); // TODO: Change the autogenerated stub
    }

    public function login(): Json
    {
        $post = $this->request->only(['type', 'code'], 'post');
        validate(UserLoginValidate::class)->check($post);
        [$isOk, $result] = $this->service->miniapplogin($post);
        return $isOk ? $this->success($result) : $this->error($result);
    }

    /**
     * 快速获取手机号码
     * @return Json
     */
    public function getPhoneNumber(): Json
    {
        $params = $this->request->only([
            'code',
            'iv',
            'encrypt_data',
        ], 'post');
        if (!$code = Arr::get($params, 'code')) {
            return $this->error('缺少参数code');
        }
//        if (!$iv = Arr::get($params, 'iv')) {
//            return $this->error('缺少参数iv');
//        }
//        if (!$encryptData = Arr::get($params, 'encrypt_data')) {
//            return $this->error('缺少参数encrypt_data');
//        }
        [$isOk, $phoneInfo] = $this->service->updatePhone($code);
        if (!$isOk) {
            return $this->error($phoneInfo);
        }
        return $this->success(['phone_number' => Arr::get($phoneInfo, 'phone')]);
    }

    /**
     * 用户上传图像
     * @return Json
     */
    public function uploadAvatar(): Json
    {
        $files = request()->file();
        if (!$targetFile = Arr::get($files, 'avatar')) {
            return $this->error('avatar不能为空');
        }
        validate(['avatar' => 'fileSize:1024000|fileExt:jpg,png,jpeg'])->check($files);
        return $this->success((new SystemUploadService())->create($targetFile, $this->getUid(0)));
    }

    /**
     * 保存更新的资源
     *
     * @return \think\Response
     */
    public function update(): \think\Response
    {
        $params = $this->request->only(['avatar', 'nickname', 'token', 'avatar_id'], 'post');
        if (!$params) {
            return $this->error('没有数据更新');
        }
        [$isOk, $result] = $this->service->update($params);
        return $isOk ? $this->success($result) : $this->error($result);
    }
}
